package sdk.webview.fmc.com.fmcsdk.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;

import com.nanchen.compresshelper.CompressHelper;

import java.io.File;
import java.io.FileOutputStream;

import sdk.webview.fmc.com.fmcsdk.BuildConfig;
import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.base.BaseActivity;
import sdk.webview.fmc.com.fmcsdk.base.BasePresenter;
import sdk.webview.fmc.com.fmcsdk.camera.BitmapUtils;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.FileUtil;
import sdk.webview.fmc.com.fmcsdk.util.ImageUtils;
import sdk.webview.fmc.com.fmcsdk.util.SdkVersionUtils;
import sdk.webview.fmc.com.fmcsdk.util.TitleBar;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.view.PaintView;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class ImageEditActivity extends BaseActivity {
    PaintView paintView;
    //图片名称
    private String iamgeName;
    Bitmap bitmap;
    Button clear_btn, ok_btn;
    TitleBar titlebar;


    @Override
    protected int getLayoutId() {
        return R.layout.imageedit;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.setStatusBarColor(ContextCompat.getColor(this, R.color.color_DC3C26)); // 设置状态栏颜色
        }
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        titlebar = (TitleBar) findViewById(R.id.titlebar);
        paintView = (PaintView) findViewById(R.id.paintview);
        clear_btn = (Button) findViewById(R.id.clear_btn);
        ok_btn = (Button) findViewById(R.id.ok_btn);
        initData();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    public void initData() {
        titlebar.setTitle(getString(R.string.iamge_edit));
        paintView.setPaintColor(Color.RED);
        iamgeName = getIntent().getStringExtra("imageName"); //1720666877850381871.jpg
        Log.e("shuchang", "iamgeName--->" + iamgeName);
        int intentType = getIntent().getIntExtra("intentType", 1);
        String locationDescribe = getIntent().getStringExtra("locationDescribe");
//		paintView.setBitmap(ImageUtils.scaleBitmap(ImageEditActivity.this, localFilePath, paintView.getWidth(), paintView.getHeight()));
//		paintView.setBitmap(BitmapFactory.decodeFile(localFilePath));

//		int degree = readPictureDegree(localFilePath);
        BitmapFactory.Options opts = new BitmapFactory.Options();//获取缩略图显示到屏幕上
        opts.inSampleSize = 2;
        Bitmap cbitmap = BitmapFactory.decodeFile(getpath(iamgeName), opts);
        int degree = ImageUtils.readPictureDegree(getpath(iamgeName));
        //如果图片是倒立的旋转过来
        if (degree == 90 || degree == 270) {
            cbitmap = ImageUtils.rotaingImageView(degree, cbitmap);
        }
        if (cbitmap == null) {
        } else {
            String appName = (String) Utility.getMetaData(this, Constant.APP_NAME);
//			if (appName.equals(Constant.APP_NAME_FMS)){
            if (intentType == 0) {
                if (TextUtils.isEmpty(locationDescribe) || locationDescribe == null) {
                    locationDescribe = getResources().getString(R.string.gps_no_data);
                }
                Bitmap b = BitmapUtils.createWaterMarkBitmap(this, cbitmap, BitmapFactory.decodeResource(getResources(), R.mipmap.dingwei_gps),
                        locationDescribe, BitmapFactory.decodeResource(getResources(), R.mipmap.icon_yanzheng), Utility.getAppName(this) + " " + getResources().getString(R.string.yan_zheng_data));
                paintView.setBitmap(b);
            } else {
                paintView.setBitmap(cbitmap);
            }
//			}else {
//				paintView.setBitmap(cbitmap);
//			}


        }

    }

    public void clear(View v) {
        paintView.clear();
    }

    public void complete(View v) {
//		if(!paintView.isMark()){
//			ImageUtils.compressIamge(this,iamgeName);
//		}else {
        bitmap = paintView.getCachebBitmap();
        File file = new File(getpath(iamgeName));

        try {
            FileOutputStream stream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
            stream.flush();
            stream.close();
//				ImageUtils.compressIamge(this,iamgeName);
//				ImageUtils.compressAndSave(this,iamgeName);
            String storePath;
            if (SdkVersionUtils.checkedAndroid_R()) {
                storePath = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");
            } else {
                storePath = context.getFilesDir().getAbsolutePath() + "/fmc/" + PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.APP_NAME, "fmsdk");

            }

            String imageSizeStr = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.IMAGE_SIZE, "80");
            try {
                if (Integer.parseInt(imageSizeStr) > 99) {
                    imageSizeStr = "80";
                }
            } catch (Exception e) {
                imageSizeStr = "80";
            }

            XLog.i(file.getPath() + "--");


            File newfile = new CompressHelper.Builder(this)
                    .setMaxWidth(1600)  // 默认最大宽度为720
                    .setMaxHeight(1600) // 默认最大高度为960
                    .setQuality(100)    // 默认压缩质量为80  Integer.parseInt(imageSizeStr)
                    .setCompressFormat(Bitmap.CompressFormat.JPEG) // 设置默认压缩为jpg格式
                    .setDestinationDirectoryPath(storePath + Constant.H5IMAGEPATH)
                    .build()
                    .compressToFile(file);

//				// TODO 压缩成功后调用，返回压缩后的图片文件
//				if(file.exists()){
//					file.delete();
//				}
//
//				newfile.mkdirs();
//            XLog.i(newfile.getPath() + "--");

            Log.e("shuchang", "newfile.getPath()--->" + newfile.getPath());

            Intent intents = new Intent();
            intents.putExtra("path", newfile.getPath());
            intents.putExtra("pathuri", Uri.fromFile(newfile).toString());
            setResult(10, intents);
            finish();
//				return newFile;

//				Luban.with(this)
//						.load(file)
//						.ignoreBy(100)
//						.filter(new CompressionPredicate() {
//							@Override
//							public boolean apply(String path) {
//								return !(TextUtils.isEmpty(path) || path.toLowerCase().endsWith(".gif"));
//							}
//						})
//						.setCompressListener(new OnCompressListener() {
//							@Override
//							public void onStart() {
//								// TODO 压缩开始前调用，可以在方法内启动 loading UI
//							}
//
//							@Override
//							public void onSuccess(File file) {
//								// TODO 压缩成功后调用，返回压缩后的图片文件
//								Intent intents=new Intent();
//								setResult(10, intents);
//								finish();
//							}
//
//							@Override
//							public void onError(Throwable e) {
//								// TODO 当压缩过程出现问题时调用
//							}
//						}).launch();
        } catch (Exception e) {
            XLog.i(e.getMessage());
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //返回键
            Intent intent = new Intent();
            setResult(0, intent);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    public static String getDiskCacheRootDir(Context context) {
        File diskRootFile;
        if (existsSdcard()) {
            diskRootFile = context.getExternalCacheDir();
        } else {
            diskRootFile = context.getCacheDir();
        }
        String cachePath = "";
        if (diskRootFile != null) {
            cachePath = diskRootFile.getPath();
        } else {
            throw new IllegalArgumentException("disk is invalid");
        }
        return cachePath;
    }

    public static Boolean existsSdcard() {
        return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) || !Environment.isExternalStorageRemovable();
    }


    private String getpath(String name) {
        String pathname = ImageUtils.getH5ImagePath(iamgeName, this);
        return pathname;
    }
}

